//
//  DetailView.swift
//  MovieAppDemo
//
//  Created by Demo on 2025/1/26.
//

import SwiftUI

struct DetailView: View {
    @State var item: MainPica = mainpicas[1]
    @Environment(\.dismiss) var dismiss
    @State var speaker: Bool = false
    @State private var scrollOffset: CGFloat = 0
    @State private var posterScale: CGFloat = 1.0
    @State private var showBarBackground: Bool = false
    @State var showScoreCard: Bool = false
    @State private var isScrolling: Bool = false
    @State private var isVideoPlaying = false
    @State private var isImageVisible: Bool = true  // 控制图片是否可见
    @State private var isVideoStarted: Bool = false  // 控制视频是否已经开始播放
    @State private var isVideoReady = false  // 控制视频是否准备好播放
    @StateObject private var viewModel = ComicDetailViewModel()
    @StateObject private var viewModel2 = MainPicaViewModel()
    @State private var hasAppeared = false
    @StateObject private var viewModelFav = FavModel()
    @State private var dominantColor: Color = Color("BgColor1")   // 初始值，后面会更新
    @StateObject private var detailPlaybackManager = DetailPlaybackManager.shared
    
    var is_fav: Int {
        viewModel.detail?.is_fav ?? 0
    }
    
    
    
    var body: some View {
        let eps_data: [ComicEps] = viewModel.detail?.eps ?? comiceps
        GeometryReader { proxy in
            ZStack(alignment: .top) {
                VideoPicView(
                    proxy: proxy,
                    isVideoReady: $isVideoReady,  // 传递绑定
                    item: $item,  // 传递绑定
                    speaker: $speaker,
                    scrollOffset: $scrollOffset,
                    posterScale: $posterScale,
                    isImageVisible: $isImageVisible,
                    isVideoStarted: $isVideoStarted,
                    isVideoPlaying: $isVideoPlaying,
                    dominantColor:$dominantColor
                )
                
                ScrollView {
                    GeometryReader { geometry in
                        Color.clear
                            .onChange(of: geometry.frame(in: .global).minY) { oldValue, value in
                                scrollOffset = value
                                
                                if value < 0 {
                                    posterScale = 1 + abs(value) / 2000  //向上滑动，图片逐渐增大
                                } else {
                                    posterScale = min(1 + value / 500, 1.5)
                                }
                                
                                // 使用动画过渡来控制背景的显示和隐藏
                                withAnimation(.easeInOut(duration: 0.6)) {
                                    if scrollOffset < -100 {
                                        showBarBackground = true
                                    } else {
                                        showBarBackground = false
                                    }
                                }
                            }
                    }
                    .frame(height: 0)
                    
                    ZStack(alignment: .top) {
                        VStack {
                            Text("\(item.name)")
                                .lineLimit(1)
                                .font(.system(size: 40, weight: .semibold))
                                .foregroundStyle(.white)
                                .padding(.horizontal, 10)
                            
                            Text("\(item.add_time)")
                                .font(.system(size: 20, weight: .semibold))
                                .foregroundStyle(.white.opacity(0.9))
                            
                            HStack {
                                ForEach(item.tags.prefix(3), id: \.self) { tag in
                                    Text(tag)
                                        .font(.system(size: 14))
                                        .foregroundStyle(.white)
                                        .padding(6)
                                        .background(Color.white.opacity(0.2))  // 背景色
                                        .clipShape(RoundedRectangle(cornerRadius: 6))  // 圆角
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 6)  // 边框的圆角
                                                .stroke(Color.white, lineWidth: 1)  // 灰色边框
                                        )
                                        .padding(.trailing, 2)  // 每个标签之间有一些间距
                                }
                                
                                HStack {
                                    Button {
                                        viewModelFav.addToFav(mainId:item.id , type: item.type){ success in
                                            viewModel.detail?.is_fav = viewModel.detail?.is_fav == 0 ? 1 : 0
                                        }
                                    } label: {
                                        Image(systemName: is_fav == 0 ? "heart" : "heart.fill")  // 点赞图标
                                            .foregroundColor(.white)  // 红色
                                            .font(.system(size: 20))  // 图标大小
                                            .padding(.leading, 20)
                                    }
                                    
                                }
                            }
                            .padding(.horizontal, 8)
                            .padding(.horizontal, 20)  // 只设置左右方向的 padding 为 20
                            
                            HStack {
                                
                                NavigationLink {
                                    // 播放按钮点击事件
                                    if item.type == 3{
                                        ComicView(item: item, ep_id: eps_data[0].id, ep_name: eps_data[0].name, is_fav: is_fav)

                                    }else{
                                        FeedView(item: item)
                                    }
                                    
                                 
                                } label: {
                                    HStack {
                                        Image(systemName: "play.fill")
                                            .font(.system(size: 20, weight: .bold))
                                        Text("立即开始观看")
                                            .font(.system(size: 25, weight: .bold))
                                            .foregroundStyle(Color("BgColor1"))
                                    }
                                    .padding(10)
                                    .foregroundColor(Color("BgColor1"))
                                    .background(.white)
                                    .clipShape(RoundedRectangle(cornerRadius: 10.0))
                                    .frame(minWidth: 150)  // 设置最小宽度
                                    .padding(.trailing, 5)  // 设置右侧间距
                                }
                                
                                Button {
                                    // 下载按钮点击事件
                                    showScoreCard.toggle()
                                } label: {
                                    Image(systemName: "arrow.down.circle.fill")
                                        .font(.system(size: 25, weight: .black))
                                        .foregroundStyle(Color("BgColor1"))
                                        .padding(10)
                                        .background(.white)
                                        .clipShape(RoundedRectangle(cornerRadius: 10.0))
                                        .padding(.leading, 5)  // 设置左侧间距
                                }
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.top, 10)
                            
                            Text("\(item.name+item.desc)").font(.system(size: 18, weight: .semibold))
                                .foregroundStyle(.white.opacity(0.8))
                                .lineLimit(3)
                                .padding(10)
                                .multilineTextAlignment(.leading)  // 确保多行文本左对齐
                        }
                        .frame(height: 300)
                        .background(
                            LinearGradient(
                                gradient: Gradient(colors: [dominantColor.opacity(0), dominantColor.opacity(0.5), dominantColor.opacity(0.7), dominantColor.opacity(1),dominantColor.opacity(1)]),
                                startPoint: .top,
                                endPoint: .bottom
                            )
                        )
                        .padding(.top, 300)
                        
                        VStack(alignment: .leading) {
                            Section {
                                VStack(alignment: .leading) {
                                    
                                    HStack {
                                        Text("剧集")
                                            .foregroundStyle(.white)
                                        Text("(\(eps_data.count))")
                                            .foregroundStyle(.white)
                                            .font(.system(size: 20, weight: .medium))
                                        Spacer()
                                    }
                                    .font(.system(size: 24, weight: .semibold))
                                    
                                    ScrollView(.horizontal) {
                                        LazyHStack(spacing: 20) {
               
                                            if item.type != 3 {
                                                
                                                DiscoverTopCard(item: item, tag: "正在观看")
                                                    .frame(width: 140, height: 160)
                                                    .onAppear {
                                                        if !hasAppeared {
                                                            // 执行首次加载的代码
                                                            viewModel2.get_tuijian(type: item.type)
                                                            hasAppeared = true
                                                        }
                                                        
                                                    }
                                                
                                            }else{
                                                
                                                
                                                ForEach(eps_data, id: \.id) { item_eps in
                                                    
                                                    NavigationLink {
                                                        ComicView(item: item, ep_id: eps_data[0].id, ep_name: eps_data[0].name, is_fav: is_fav)

                                                    } label: {
                                                        EpCard(item: item_eps, tag: "已看20%")
                                                            .frame(width: 140, height: 100)
                                                    }
                                                    
                                                }
                                                
                                                
                                            }
                                            
                                        }
                                    }
                                }
                                
                                .padding()
                            }
                            
                            Section {
                                VStack(alignment: .leading) {
                                    HStack {
                                        Text("相关推荐")
                                            .foregroundStyle(.white)
                                    }
                                    .font(.system(size: 24, weight: .semibold))
                                    
                                    ScrollView(.horizontal) {
                                        LazyHStack(spacing: 20) {
                                            
                                            ForEach(viewModel2.tuijian, id: \.id) { item in
                                                NavigationLink {
                                                    DetailView(item: item)
                                                } label: {
                                                    DiscoverTopCard(item: item, tag: "")
                                                        .frame(width: 200, height: 200)
                                                }
                                            }
                                        }
                                    }
                                    .frame(height: 200)
                                }
                                .padding()
                            }
                        }
                        .background(dominantColor)
                        .frame(width: proxy.size.width)
                        .background(dominantColor)
                        .padding(.top, 600)
                        
                    }
                }
                .ignoresSafeArea(.all)
                .scrollIndicators(.hidden) // 隐藏滚动条
                
                if showBarBackground {
                    DetailBar(
                        proxy: proxy,
                        isVideoReady: $isVideoReady,  // 传递绑定
                        item: $item,  // 传递绑定
                        speaker: $speaker,
                        scrollOffset: $scrollOffset,
                        posterScale: $posterScale,
                        isImageVisible: $isImageVisible,
                        isVideoStarted: $isVideoStarted,
                        isVideoPlaying: $isVideoPlaying
                    )
                }
            }
            .onAppear {
                if !hasAppeared {
                    // 执行首次加载的代码
                    viewModel.get_detail(main_id:item.id)
                    viewModel2.get_tuijian(type: item.type)
                    hasAppeared = true
                    
                    // 立即开始播放详情页面的视频
                    if item.type != 3 {  // 只有非漫画类型才播放视频
                        detailPlaybackManager.startPlaying(videoId: String(item.id))
                        print("🎬 DetailView 启动视频播放: \(item.id)")
                    }
                }
            }
            .background(dominantColor)
            .frame(height: proxy.size.height)
            .animation(.default, value: showBarBackground)
            .navigationBarBackButtonHidden()
        }
        
        
    }
    
    
}



#Preview {
    NavigationView {
        DetailView()
    }
}
